package com.koron.common.core.business.todoApproval.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 待审自动化
 *
 * @author jzp
 * @since 2023/3/31
 */
@Slf4j
public class TodoAutomation {

    private final static String arguments = "1693932973188845568";

    /**
     * 清除OA上的待办
     * @param env 0测试环境 1正式环境
     * @param accounts 需要清除待办的账号
     */
    public void clearOaTodo(int env, String[] accounts) {
        TodoTest todoTest = new TodoTest(env);
        for (String account : accounts) {
            todoTest.setLoginName(account);
            // 获取待办
            String res = todoTest.getTodo();
            JSONObject result = JSONUtil.parseObj(res);
            if (result.getInt("returnState") == 1) {
                throw new IllegalArgumentException("待审服务异常：" + result.getStr("message"));
            }

            JSONObject message = result.getJSONObject("message");
            if (message == null || message.getStr("docs") == null) {
                log.info("未找到该账号：【" + account + "】的待办数据");
                continue;
            }
            JSONArray docs = message.getJSONArray("docs");
            // 拿到所有的业务id
            List<String> modelIds = IntStream.range(0, docs.size()).mapToObj(docs::getJSONObject).map(e -> e.getStr("modelId")).collect(Collectors.toList());

            // 转已办
            for (String modelId : modelIds) {
                log.info("转已办，account：" + account + "，id：" + modelId);
                todoTest.setTodoDone(modelId, account);
            }
        }
    }

    @SneakyThrows
    public void clearOaTodoByIds(int env, String[] modelIds) {
        TodoTest todoTest = new TodoTest(env);
        // 转已办
        for (String modelId : modelIds) {
            log.info("转已办，id：" + modelId);
            todoTest.setTodoDone(modelId);
            Thread.sleep(100);
        }
    }

    @SneakyThrows
    public void clearOaTodoByAccountAndIds(int env, String account, String[] modelIds) {
        TodoTest todoTest = new TodoTest(env, account);
        // 转已办
        for (String modelId : modelIds) {
            log.info("转已办，id：" + modelId);
            todoTest.setTodoDone(modelId, account);
            Thread.sleep(100);
        }
    }

    public void clearOaTodo(int env, List<String> accounts) {
        String[] arr = new String[accounts.size()];
        accounts.toArray(arr);
        clearOaTodo(env, arr);
    }

}
